package com.tally.business.controller;

import com.alibaba.fastjson.JSONObject;
import com.tally.server.config.ConstKey;
import com.tally.server.dto.LoginUserDTO;
import com.tally.server.exception.ValidatorException;
import com.tally.server.utils.DateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @Author: sy
 * @Date: 2020/12/30 12:55
 * @Description:
 */
public class BusinessController {
    private static final Logger logger = LoggerFactory.getLogger(BusinessController.class);

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private HttpServletRequest request;

    /**
     * 字符串转整型
     * @param s
     * @return
     */
    protected int parseInt(String s){
        int i;
        try{
            i = Integer.parseInt(s);
        }catch (NumberFormatException e){
            throw new ValidatorException(s + "非纯数字！");
        }
        return i;
    }

    /**
     * 得到日期中的年月
     * @param date
     * @return
     */
    protected int[] getYearAndMonth(Date date){
        Calendar calendar = DateUtil.getCalendar(date);
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH) + 1;
        return new int[]{year,month};
    }

    /**
     *
     * @param pattern s代表参数占位，以空格分隔，*代表全部匹配  pattern = s * s s s
     * @param params 参数列表 [ConstKey.GRAPH_INCOME_PREFIX, userId, year, month]
     * @return ConstKey.GRAPH_INCOME_PREFIX + "-*-" + userId + "-" + year + "-" + month
     */
    protected String generateKey(String pattern, String... params){
        if(StringUtils.isEmpty(pattern) || params.length == 0){
            return null;
        }
        pattern = pattern.trim();
        String[] paramKeys = pattern.split(" ");
        StringBuilder sb = new StringBuilder();
        int index=0;

        for(String p: paramKeys){
            p = p.trim();
            if("*".equals(p)){
                sb.append("*-");
            }else{
                String s;
                try{
                    s = params[index++];
                }catch (IndexOutOfBoundsException e){
                    logger.warn("匹配表达式生成有误");
                    return null;
                }
                sb.append(s).append("-");
            }
        }
        sb.deleteCharAt(sb.length()-1);
        return sb.toString();
    }

    protected JSONObject getLoginUser() {
        String token = request.getHeader("token");
        String jsonString =(String) redisTemplate.opsForValue().get(token + ConstKey.LOGIN_SUFFIX);
        return JSONObject.parseObject(jsonString);
    }
}
